package com.xuecheng.publish.listener;

import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.JsonUtil;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.publish.common.constant.CoursePublishErrorCode;
import com.xuecheng.publish.entity.CoursePubMsg;
import com.xuecheng.publish.service.CoursePubService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class PublishPageConsumer {

    @Autowired
    private CoursePubService coursePubService;

    /**
     * 订阅课程发布消息
     *
     * @param jsonString
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "${course.publish.queue}"),
                    exchange = @Exchange(value = "${course.publish.exchange}"),
                    key = "${course.publish.routingkey}"
            )})
    public void getPublishConsumer(String jsonString) {
        log.info("course consumer, {}", jsonString);

        // 判断消息是否为空
        if (StringUtil.isBlank(jsonString)) {
            ExceptionCast.cast(CoursePublishErrorCode.E_120203);
        }

        // 将消息转为对象
        CoursePubMsg coursePubMsg = null;
        try {
            coursePubMsg = JsonUtil.jsonToObject(jsonString, CoursePubMsg.class);
        } catch (Exception e) {
            log.error("课程发布消息转换失败 => {}, msg => {}", e.getMessage(), jsonString);
            ExceptionCast.castWithException(CoursePublishErrorCode.E_120215, e);
        }
        // 调用service，完成本地事务
        coursePubService.publishPage(coursePubMsg);
    }
}
